<!-- 起草合同 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew :title="title" showBack> </pageHeaderNew>
    </template>
    <div class="template-steps" v-if="templateData.data.preData.length > 0">
      <a-steps changeable :current="current" @change="setCurrent">
        <!-- <a-step>合同信息</a-step> -->
        <a-step>合同变更原因</a-step>
        <a-step>合同编辑</a-step>
        <a-step>合同预览</a-step>
      </a-steps>
    </div>
    <!-- 基础信息 -->
    <!-- <div v-show="current === 1">
      <ContractBaseInfo ref="baseInfoRef" v-model:data="templateData.data" />
    </div> -->
    <!-- 合同原因 -->
    <div v-show="current === 1">
      <ContractReason ref="signRef" v-model:data="templateData.data" />
    </div>
    <!-- 合同文本 -->
    <div v-show="current === 2">
      <ContractDesign ref="designRef" v-model:data="templateData.data" />
    </div>
    <!-- 合同预览 -->
    <div v-show="current === 3">
      <!-- <AssessmentIndex v-model:data="templateData" /> -->
      <ContractPreview v-model:data="templateData.data" />
    </div>

    <footer>
      <a-space>
        <a-button
          class="btn"
          type="secondary"
          :disabled="current <= 1"
          @click="onPrev"
        >
          <IconLeft />
          上一步
        </a-button>
        <a-button
          class="btn"
          type="primary"
          v-show="current !== 4"
          :disabled="current >= 4"
          @click="onNext"
        >
          下一步
          <IconRight />
        </a-button>
        <a-button
          class="btn"
          type="outline"
          v-show="current === 3"
          @click="save"
        >
          确认并保存
        </a-button>
        <a-button
          class="btn"
          type="primary"
          v-show="current === 3"
          @click="send"
        >
          确认发起
        </a-button>
      </a-space>
    </footer>
  </ContentCard>
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import dayjs from 'dayjs';
import { changeControlData } from '@/utils/control';
import { PerformanceAppraisal } from '@/apis/management/performance/baseSetting/template/type';
import { GetHumanRosterDetail } from '@/apis/management/human/humanChange/leave';
import {
  SwitchDraftWaitSignedContract,
  DraftWaitSignedContractSave,
  DraftWaitSignedContractSavePutStatus,
  GetGenerateContractNum,
  DraftWaitSignedContractSavePut,
  GetUserContractByStatusDetail
} from '@/apis/management/contract/contractManagement/waitSigned';
import { ChangeContract } from '@/apis/management/contract/contractManagement/haveSigned';
import { GetBusinessModalData } from '@/apis/controltotal';
import ContractBaseInfo from './ContractBaseInfo.vue';
import ContractDesign from './ContractDesign.vue';
import ContractReason from './ContractReason.vue';
import ContractPreview from './ContractPreview.vue';
import { Message } from '@arco-design/web-vue';
import { useVModel } from '@vueuse/core';
import router from '@/router';

const props = withDefaults(
  defineProps<{
    data?: PerformanceAppraisal;
  }>(),
  {}
);
// const emit = defineEmits(['update:visible', 'update:data', 'handleOk', 'save']);
const route = useRoute();
const userId = +route.query.userId;
const title = '合同变更';

let baseInfoRef = ref(); // 基础信息ref
let designRef = ref(); // 合同编辑ref
let signRef = ref(); // 合同签署ref
let pageHeaderSettingRef = ref();
let fileSettingRef = ref();
const templateData = reactive({
  data: {
    userData: [],
    baseInfoData: {
      companyId: undefined, // 企业签署方id
      templateTypeId: undefined, // 合同的typeid
      templateId: undefined, // 合同id
      templateName: '', // 合同名称
      templateInfo: {}, // 合同模板详情信息
      // 合同模板其他信息
      // templateInfo: {
      //   enterpriseName: '', // 企业名称
      //   logo: '', // 企业logo
      //   style: 1 // 模板页眉样式
      // },
      annexData: [], // 附件信息
      annexName: [], // 附件名称
      remark: ''
    },
    designData: [],
    preData: [], // 变更前的数据
    preViewData: [], // 预览数据
    signData: [
      {
        contractName: ``, // 合同名称
        contractNum: '', // 合同编号
        way: 1, // 签署方式
        overTime: '', // 合同确认截止日期
        expire: 1, // 确认截止日期未确认将视为
        signature: '', // 合同签署有效时间
        remindTime: '', // 提醒时间
        remind: undefined // 有效期前几天开始提醒
      }
    ]
  }
});
// 获取人员信息
const getUserData = async () => {
  try {
    const res = await GetHumanRosterDetail({
      id: userId
    });
    templateData.data.userData.push(res);
  } catch (error: unknown) {
    console.log(error);
  }
};
getUserData();

let controlList = ref([]); // 储存控件数据

// 获取起草合同详情
const getData = async () => {
  try {
    const [res, controlRes]: any[] = await Promise.all([
      // 获取合同详情
      GetUserContractByStatusDetail({
        userId: userId,
        status: 6
      }),
      GetBusinessModalData({
        funcCode: 'SER_FUNC751D0BFF5DF442209D437EE9A581693E'
      })
    ]);

    controlList.value = changeControlData(controlRes.funcCtlInfos, 'ctlDetail');
    templateData.data.baseInfoData.companyId = res[0].companyId;
    templateData.data.baseInfoData.id = res[0].id;
    templateData.data.baseInfoData.templateId = res[0].children[0].id;
    templateData.data.baseInfoData.templateTypeId = res[0].children[0].typeId;
    templateData.data.baseInfoData.templateName = res[0].children[0].name;
    templateData.data.baseInfoData.templateInfo = res[0].children[0];
    templateData.data.baseInfoData.remark = res[0].remark;
    for (let i = 1; i < res[0].children.length; i++) {
      templateData.data.baseInfoData.annexData.push(res[0].children[i]);
      templateData.data.baseInfoData.annexName.push(res[0].children[i].name);
    }
    templateData.data.signData[0] = Object.assign({
      contractName: res[0].contractName,
      contractNum: res[0].contractNum,
      way: res[0].way,
      overTime: res[0].overTime,
      expire: res[0].expire,
      signature: res[0].signature,
      remind: res[0].remind,
      remindTime: res[0].remindTime
    });
    templateData.data.preData = cloneDeep(res[0].children);
    for (let i of templateData.data.preData) {
      i.text = await switchCodes(i);
    }

    console.log(templateData.data, 'templateData.data');
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

const current = ref(1);
const reset = () => {
  current.value = 1;
};
const onPrev = () => {
  current.value = Math.max(1, current.value - 1);
};
const onNext = async () => {
  // const check = await baseInfoRef.value.validate();
  // if (check) return;
  current.value = Math.min(4, current.value + 1);
  if (current.value === 2) {
    const res = await designRef.value.tabs.data;

    // 过滤出非空的元素
    const nonEmptyRes = cloneDeep(res.filter((i) => i));
    for (let i of nonEmptyRes) {
      for (let i2 in i) {
        i[i2].text = await switchCodes(i[i2]);
      }
    }
    templateData.data.preViewData = nonEmptyRes;
  }
};
const setCurrent = async (n: number) => {
  current.value = n;
  if (current.value === 2) {
    const res = await designRef.value.tabs.data;

    // 过滤出非空的元素
    const nonEmptyRes = cloneDeep(res.filter((i) => i));
    for (let i of nonEmptyRes) {
      for (let i2 in i) {
        i[i2].text = await switchCodes(i[i2]);
      }
    }
    templateData.data.preViewData = nonEmptyRes;
  }
};

const checkValidate = async (validate: any) => {
  // console.log('=================================await validate()===');
  // console.log(await validate());
  // console.log('====================================');
  if (await validate()) return true;
  else return false;
};

// 将控件名字转换成控件code
const switchCodes = async (data: any) => {
  try {
    controlList.value.forEach((item: any) => {
      let regexp = new RegExp(`#${item.ctlCnName}#`, 'g');
      // currTemplate.value = currTemplate.value.replace(regexp, `#${item.cnName}#`);
      data.text = data.text.replace(regexp, `#${item.ctlCode}#`);
    });
    if (data.style !== 3) {
      const header = `<h3 style="text-align: ${
        data.style === 2 ? 'center' : 'left'
      }"><img src="${
        data.logo
      }" style="width: 40px; height: 40px; border-radius: 50%;"/> ${
        data.enterpriseName
      }</h3><br/>`;

      data.text = header + data.text;
    }
    const res = await SwitchDraftWaitSignedContract({
      id: data.userInfo?.id || userId,
      text: data.text,
      codes: data.codes
    });
    return res;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 获取合同预警时间
const countRemindDate = (date: string, num: number) => {
  const tempDay = dayjs(date);
  const result = tempDay.subtract(num, 'day');
  return result.format('YYYY-MM-DD');
};

// 获取合同编号
const getContractNum = async (id: number, userId: number) => {
  try {
    const res = await GetGenerateContractNum({
      id,
      userId
    });
    return res;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 判断一个对象属性是否为空
function hasEmptyPropertyValue(obj) {
  for (let key in obj) {
    // eslint-disable-next-line no-prototype-builtins
    if (obj.hasOwnProperty(key)) {
      if (key !== 'contractNum' && key !== 'remindTime') {
        if (!obj[key]) {
          return true;
        }
      }
    }
  }
  return false;
}

// 确认并保存
const save = async () => {
  try {
    console.log('====================================templateData');
    console.log(templateData.data);
    console.log(Object.values(templateData.data.preViewData[0]));
    console.log('====================================');
    templateData.data.designData = cloneDeep(
      designRef.value.tabs.data.filter((i) => i)
    );
    let contractList = {};
    for (let i = 0; i < templateData.data.userData.length; i++) {
      let children = [];
      Object.values(templateData.data.designData[i]).forEach((el: any) => {
        children.push(el);
      });
      // templateData.data.signData[i].contractNum = await getContractNum(
      //   templateData.data.baseInfoData.templateTypeId,
      //   templateData.data.userData[i].id
      // );
      templateData.data.signData[i].remindTime = countRemindDate(
        templateData.data.signData[i].signature,
        templateData.data.signData[i].remind
      );
      contractList = {
        userId: templateData.data.userData[i].id,
        companyId: templateData.data.baseInfoData.companyId,
        templateId: templateData.data.baseInfoData.templateId,
        typeId: templateData.data.baseInfoData.templateTypeId,
        remark: templateData.data.baseInfoData.remark,
        children,
        status: 1,
        isChang: 1,
        contractName: templateData.data.signData[i].contractName,
        contractNum: templateData.data.signData[i].contractNum,
        way: templateData.data.signData[i].way,
        overTime: templateData.data.signData[i].overTime,
        expire: templateData.data.signData[i].expire,
        signature: templateData.data.signData[i].signature,
        remindTime: templateData.data.signData[i].remindTime,
        remind: templateData.data.signData[i].remind
      };
    }
    console.log(contractList);
    // await Promise.all([
    //   ChangeContract(contractList),
    //   DraftWaitSignedContractSavePutStatus({
    //     ids: [userId],
    //     status: 3
    //   })
    // ]);
    router.back();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 确认发起
const send = async () => {
  try {
    //
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style lang="less" scoped>
.template-steps {
  padding: 0 160px;
  margin-bottom: 60px;
}
footer {
  height: 100px;
  padding-top: 15px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
</style>
